// Copyright (c) 2010 Manuel Peinado Gallego <manuel.peinado@gmail.com>
// Distributed under the MIT license


// LogManager.cpp : implementation of the LogManager class
//

#include "stdafx.h"
#include "WorldBuilder.h"
#include "LogManager.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


LogManager::LogManager()
{
}

void LogManager::addLogListener(LogListener* listener)
{
    ASSERT(m_listeners.find(listener) == m_listeners.end());
    m_listeners.insert(listener);
}

void LogManager::removeLogListener(LogListener* listener)
{
    ASSERT(m_listeners.find(listener) != m_listeners.end());
    m_listeners.erase(listener);
}

void LogManager::notifyListeners()
{
    ASSERT(!m_logMessages.empty());

    typedef std::set<LogListener*>::iterator It;
    for(It it = m_listeners.begin(); it != m_listeners.end(); ++it)
    {
        (*it)->onMessage(this, m_logMessages.front());
    }
}

void LogManager::addLogMessage(const std::string & msg)
{
    TCHAR timeBuff[32];
    TCHAR dateBuff[32];

    SYSTEMTIME sysTime;
    ::GetLocalTime(&sysTime);
    ::GetDateFormatEx(NULL, DATE_SHORTDATE, &sysTime, NULL, dateBuff, 32, NULL);
    ::GetTimeFormat(NULL, 0, &sysTime, 0, timeBuff, 32);

    CString mfcMsg;
    mfcMsg.Format(_T("[%s %s] %s"), dateBuff, timeBuff, CString(msg.c_str()));

    m_logMessages.push_front((const char*)CStringA(mfcMsg));

    notifyListeners();

}
